package com.camemax.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

/**
 * Channel本地文件读测试：
 * 使用ByteBuffer（缓冲）与FileChannel（通道），读取file01.txt内容
 * File => Channel => Buffer
 * FileInputStream（读取文件内容） => FileChannel => ByteBuffer
 */
public class NIOChannelForRead {

    static String NIO_FILE_PATH = "D:\\Javas\\netty\\files\\file01.txt";
    public static void main(String[] args) {

        // 1、创建缓冲区,
        long length = new File(NIO_FILE_PATH).length();
        System.out.println("文件长度" + length);
        ByteBuffer buffer = ByteBuffer.allocate((int)length);
        try {
            FileInputStream fileStream = new FileInputStream(NIO_FILE_PATH);
            FileChannel channel = fileStream.getChannel();
            channel.read(buffer); // 将数据从通道读取到缓冲区，数据流向：Channel => Buffer
            System.out.println(new String(buffer.array(), StandardCharsets.UTF_8));
            // 关闭流
            fileStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
